﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using MetroCashLib;
using MetroCashLib.DataBussiness;
using MetroCashLib.DataInfo;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MetroCash
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class PAccountBrowse : MetroCash.Common.LayoutAwarePage
    {
        private Account account;
        private String profileName;
        public PAccountBrowse()
        {
            this.InitializeComponent();

            Loaded += PAccountBrowse_Loaded;
        }

        void PAccountBrowse_Loaded(object sender, RoutedEventArgs e)
        {
            this.pageTitle.Text = this.account.Name;
            ObservableCollection<Account> accounts = new ObservableCollection<Account>(MetroCashLib.DataBussiness.BAccount.getChildAccounts(this.profileName, this.account));
            this.lstAccount.DataContext = accounts;
            //Window.Current.CoreWindow.PointerWheelChanged += CoreWindow_PointerWheelChanged;
        }

        void CoreWindow_PointerWheelChanged(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.PointerEventArgs args)
        {
            throw new NotImplementedException();
        }



        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (navigationParameter != null)
            {
                this.account = (navigationParameter as Account);
                Windows.Storage.ApplicationDataContainer roamingSetting = Windows.Storage.ApplicationData.Current.RoamingSettings;
                if (roamingSetting.Values[SettingStrings.ROAMING_CURRENT_PROFILE] != null)
                {
                    this.profileName = roamingSetting.Values[SettingStrings.ROAMING_CURRENT_PROFILE].ToString();
                }
            }
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void lstAccount_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            Account selectedAccount = e.ClickedItem as Account;
            Windows.Storage.ApplicationDataContainer roamingSetting = Windows.Storage.ApplicationData.Current.RoamingSettings;
            if (roamingSetting.Values[SettingStrings.ROAMING_ACCOUNT_BREADCRUMB] != null)
            {
                //(roamingSetting.Values[SettingStrings.ROAMING_ACCOUNT_BREADCRUMB] as Stack<Account>).Push(selectedAccount);

            }
            if (selectedAccount.isPlaceHolder)
            {
                this.Frame.Navigate(typeof(PAccountBrowse), selectedAccount);
            }
        }

        private void btnCreateAccount_Click_1(object sender, RoutedEventArgs e)
        {
            Account[] parameter = new Account[] { this.account, null };
            if (this.Frame != null)
            {
                this.Frame.Navigate(typeof(PAccountDetail), parameter);
            }
        }

        private void appbarBotom_Opened_1(object sender, object e)
        {
            //this.contentView.Margin = new Thickness() { Bottom = 84 };
        }

        //private void StackPanel_PointerWheelChanged_1(object sender, PointerRoutedEventArgs e)
        //{
        //    Debug.WriteLine("Scroll!!");
        //}

        private void appbarBotom_Closed_1(object sender, object e)
        {
            //this.contentView.Margin = new Thickness();
        }

        private void lstAccount_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as GridView).SelectedItems.Count > 0)
            {
                this.appbarBotom.IsSticky = true;
                this.appbarBotom.IsOpen = true;
                if ((sender as GridView).SelectedItems.Count > 1)
                {
                    this.btnAppBarEdit.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
                else
                {
                    this.btnAppBarEdit.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
            }
            else
            {
                this.appbarBotom.IsSticky = false;
                this.appbarBotom.IsOpen = false;
            }
        }

        private void btnAppBarClear_Click_1(object sender, RoutedEventArgs e)
        {
            this.lstAccount.SelectedItems.Clear();
        }

        private void btnAppBarEdit_Click_1(object sender, RoutedEventArgs e)
        {
            var selectedItems = this.lstAccount.SelectedItems;
            if (selectedItems.Count == 1)
            {
                Account[] parameter = new Account[] { this.account, selectedItems[0] as Account };
                if (this.Frame != null)
                {
                    this.Frame.Navigate(typeof(PAccountDetail), parameter);
                }
            }
        }

        async private void btnAppBarDelete_Click_1(object sender, RoutedEventArgs e)
        {
            var selectedItems = this.lstAccount.SelectedItems;
            if (selectedItems.Count > 0)
            {
                bool continueDelete = false;
                MessageDialog msg = new MessageDialog("Do you want to delete these accounts?", "Deletion confirmation");
                msg.Commands.Add(new UICommand("Delete", (UICommandInvokedHandler) => {
                    continueDelete = true;
                }));
                msg.Commands.Add(new UICommand("Cancel"));
                await msg.ShowAsync();
                if (continueDelete)
                {
                    for (int i = selectedItems.Count; i > 0; i--)
                    {
                        BAccount.deleteAccount(this.profileName, selectedItems[i - 1] as Account);
                        (this.lstAccount.DataContext as ObservableCollection<Account>).Remove(selectedItems[i - 1] as Account);
                    }
                }
                //(this.lstAccount.DataContext as ObservableCollection<Account>)
            }
        }
    }
}
